package com.matthewmadson.util.configurator;

import java.util.Iterator;
import java.util.PriorityQueue;
import java.util.Queue;

public class ConfigFile
implements Iterable<Location>, Iterator<Location>
{
	private boolean isRequired;
	private String name;
	Queue<Location> locations; 

	public ConfigFile(final String name)
	{
		this.isRequired = false;
		this.setName(name);
		locations = new PriorityQueue<Location>();
	}

	public void setCommandLineOption(final String cmdlnFlag, final int priority)
	{
		locations.add(new Location(cmdlnFlag, priority, LocationType.COMMAND_LINE));
	}

	public void setExternalFileLocation(final String pathToExternalFile, final int priority)
	{
		locations.add(new Location(pathToExternalFile, priority, LocationType.EXTERNAL));
	}

	public void setInternalFileLocation(final String resourcePackage, final String resourceFileName, final int priority)
	{
		locations.add(new Location(resourcePackage, resourceFileName, priority, LocationType.INTERNAL));
	}

	public void setRequired(final boolean isRequired)
	{
		this.isRequired = isRequired;
	}
	
	public boolean isRequired()
	{
		return this.isRequired;
	}
	
	public Iterable<Location> getLocations()
	{
		return this;
	}

	private void setName(String name)
	{
		this.name = name;
	}

	public String getName()
	{
		return name;
	}

	public Iterator<Location> iterator()
	{
		return this;
	}

	public boolean hasNext()
	{
		return this.locations.peek() != null;
	}

	public Location next()
	{
		return this.locations.poll();
	}

	public void remove()
	{
		throw new UnsupportedOperationException();
	}

	@Override
	public String toString()
	{
		return this.name;
	}

	@Override
	public int hashCode()
	{
		final int prime = 31;
		int result = 1;
		result = prime * result + (isRequired ? 1231 : 1237);
		result = prime
			* result
			+ ((locations == null) ? 0 : locations.hashCode());
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj)
	{
		if(this == obj)
			return true;
		if(obj == null)
			return false;
		if(getClass() != obj.getClass())
			return false;
		ConfigFile other = (ConfigFile) obj;
		if(isRequired != other.isRequired)
			return false;
		if(locations == null)
		{
			if(other.locations != null)
				return false;
		}
		else if(!locations.equals(other.locations))
			return false;
		if(name == null)
		{
			if(other.name != null)
				return false;
		}
		else if(!name.equals(other.name))
			return false;
		return true;
	}
}
